<template>
  <view class="receive-page">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">待阅发文</text>
      </view>
      <view class="nav-right"> </view>
    </view>

    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-form">
        <input class="search-input" v-model="searchForm.title" placeholder="请输入公文标题" />
        <view class="search-buttons">
          <text class="search-btn" @click="handleSearch">查询</text>
          <text class="reset-btn" @click="handleReset">重置</text>
        </view>
      </view>
    </view>

    <!-- 状态切换（未阅读/已阅读） -->
    <view class="status-switch">
      <view
        class="status-tab"
        :class="{ active: searchForm.read === 0 }"
        @click="switchReadState(0)"
      >
        <u-icon
          name="clock"
          :color="searchForm.read === 0 ? '#ffffff' : '#666666'"
          size="18"
        ></u-icon>
        <text class="tab-text">未阅读</text>
      </view>
      <view
        class="status-tab"
        :class="{ active: searchForm.read === 1 }"
        @click="switchReadState(1)"
      >
        <u-icon
          name="checkmark-circle"
          :color="searchForm.read === 1 ? '#ffffff' : '#666666'"
          size="18"
        ></u-icon>
        <text class="tab-text">已阅读</text>
      </view>
    </view>

    <!-- 收文列表 -->
    <view class="list-section">
      <view class="list-header">
        <text class="list-title">{{ searchForm.read === 0 ? '待阅读文件' : '已阅读文件' }}</text>
        <text class="list-count">共{{ pagination.total }}条</text>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-else-if="documentList.length === 0">
        <text class="empty-icon">📭</text>
        <text class="empty-text">{{
          searchForm.read === 0 ? '暂无待阅读文件' : '暂无已阅读文件'
        }}</text>
      </view>

      <!-- 文件列表 -->
      <view class="receive-list" v-else>
        <view
          class="receive-item"
          v-for="item in documentList"
          :key="item.id"
          @click="handleView(item)"
        >
          <view class="item-header">
            <view class="item-title-row">
              <text class="title-text">{{ item.sourceDocumentTitle || '无标题' }}</text>
              <view class="read-badge" :class="{ read: item.isRead === 1 }">
                <text class="badge-text">{{ item.isRead === 1 ? '已读' : '未读' }}</text>
              </view>
            </view>
            <text class="item-time">{{
              formatDateTime(item.receiveDocumentTime || item.createdAt)
            }}</text>
          </view>
          <view class="item-content">
            <text class="item-desc" v-if="item.receiveDocumentSymbol">
              文件字号：{{ item.receiveDocumentSymbol }}
            </text>
            <text class="item-desc" v-if="item.sourceDocumentNumber">
              来源文号：{{ item.sourceDocumentNumber }}
            </text>
            <text class="item-desc" v-if="item.receiveDeptName">
              接收部门：{{ item.receiveDeptName }}
            </text>
          </view>
          <view class="item-footer">
            <text class="view-btn">查看详情 ›</text>
          </view>
        </view>
      </view>

      <!-- 分页加载更多 -->
      <view class="load-more" v-if="!loading && documentList.length > 0 && hasMore">
        <text class="load-more-text" @click="loadMore">加载更多</text>
      </view>
      <view class="no-more" v-if="!loading && documentList.length > 0 && !hasMore">
        <text class="no-more-text">没有更多了</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getMyInternalReceiveDocuments, markInternalReceiveAsRead } from '@/Api/receive'
import { UserManager } from '@/utils/user'

// 响应式数据
const loading = ref(false)
const documentList = ref<any[]>([])

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0,
})

// 计算是否还有更多数据
const hasMore = ref(true)

// 搜索表单
const searchForm = reactive<any>({
  title: '',
  read: 0, // 0-未读，1-已读
  readStatus: 0, // 0-未读，1-已读
})

/**
 * 切换阅读状态
 */
const switchReadState = (state: number) => {
  searchForm.read = state
  searchForm.readStatus = state
  pagination.current = 1
  loadData()
}

/**
 * 加载内部单位收文列表
 */
const loadData = async () => {
  loading.value = true
  try {
    const userInfo = UserManager.getFullUserInfo()
    const params = {
      ...searchForm,
      pageNum: pagination.current,
      pageSize: pagination.size,
      userId: Number(userInfo?.id),
      readStatus: searchForm.readStatus,
    }
    const response = await getMyInternalReceiveDocuments(params)
    if (response.code === 200) {
      const data = response.data
      documentList.value = data.records || data || []
      pagination.total = data.total || documentList.value.length

      // 判断是否还有更多数据
      hasMore.value = documentList.value.length < pagination.total
    }
  } catch (error) {
    console.error('获取内部单位收文列表失败:', error)
    uni.showToast({
      title: '获取列表失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

/**
 * 重置
 */
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    read: 0,
    readStatus: 0,
  })
  pagination.current = 1
  loadData()
}

/**
 * 加载更多
 */
const loadMore = async () => {
  if (loading.value || !hasMore.value) return

  pagination.current++
  loading.value = true

  try {
    const userInfo = UserManager.getFullUserInfo()
    const params = {
      ...searchForm,
      pageNum: pagination.current,
      pageSize: pagination.size,
      userId: Number(userInfo?.id),
      readStatus: searchForm.readStatus,
    }
    const response = await getMyInternalReceiveDocuments(params)
    if (response.code === 200) {
      const data = response.data
      const newList = data.records || data || []
      documentList.value = [...documentList.value, ...newList]
      pagination.total = data.total || documentList.value.length

      // 判断是否还有更多数据
      hasMore.value = documentList.value.length < pagination.total
    }
  } catch (error) {
    console.error('加载更多失败:', error)
    pagination.current-- // 恢复页码
  } finally {
    loading.value = false
  }
}

/**
 * 查看详情（跳转到详情页面）
 */
const handleView = async (row: any) => {
  try {
    console.log('[handleView] 点击查看详情，row:', row)

    // 如果是未读状态，先标记为已读
    if (row.isRead === 0) {
      try {
        const response = await markInternalReceiveAsRead(row.id)
        if (response.code === 200) {
          console.log('[handleView] 标记已读成功')
          // 更新本地数据状态
          row.isRead = 1
          row.readAt = new Date().toISOString()

          // 更新列表中的状态
          const index = documentList.value.findIndex((item) => item.id === row.id)
          if (index !== -1) {
            documentList.value[index] = { ...row }
          }
        }
      } catch (error) {
        console.warn('[handleView] 标记已读失败:', error)
        // 标记已读失败不影响查看详情
      }
    }
    // 跳转到发文详情页面（传递源文档ID）
    console.log('[handleView] 跳转到发文详情页，sourceDocumentId:', row.sourceDocumentId)
    uni.navigateTo({
      url: `/pages/document/send/detail?id=${row.sourceDocumentId}&source=internalReceive`,
      fail: () => {
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none',
        })
      },
    })
  } catch (error) {
    console.error('[handleView] 查看详情异常:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none',
    })
  }
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

/**
 * 返回上一页
 */
const goBack = () => {
  uni.navigateBack()
}

// 页面加载时获取数据
onMounted(async () => {
  await UserManager.ensureUserInfo()
  loadData()
})
</script>

<style lang="scss" scoped>
.receive-page {
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 顶部导航 */
.nav-header {
  background: #1678ff;
  padding: 46px 32rpx 20rpx 32rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: white;
  flex-shrink: 0;

  .nav-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .back-icon {
      font-size: 40rpx;
      font-weight: bold;
    }
  }

  .nav-center {
    flex: 1;
    text-align: center;

    .nav-title {
      font-size: 36rpx;
      font-weight: bold;
    }
  }

  .nav-right {
    min-width: 22px;
  }
}

/* 搜索区域 */
.search-section {
  padding: 12rpx 32rpx;
  background: white;
  position: relative;
  z-index: 3;

  .search-form {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .search-input {
      flex: 1;
      height: 80rpx;
      padding: 0 24rpx;
      border: 1rpx solid #e5e7eb;
      border-radius: 12rpx;
      font-size: 28rpx;
      background: #f8f9fa;
    }

    .search-buttons {
      display: flex;
      gap: 16rpx;

      .search-btn,
      .reset-btn {
        padding: 16rpx 32rpx;
        border-radius: 12rpx;
        font-size: 26rpx;
        text-align: center;
      }

      .search-btn {
        background: #1678ff;
        color: white;
      }

      .reset-btn {
        background: #f3f4f6;
        color: #666;
      }
    }
  }
}

/* 状态切换 */
.status-switch {
  padding: 12rpx 32rpx 0;
  display: flex;
  gap: 16rpx;

  .status-tab {
    flex: 1;
    padding: 20rpx;
    background: white;
    border-radius: 12rpx;
    text-align: center;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;

    &.active {
      background: #1678ff;
      box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.4);

      .tab-icon,
      .tab-text {
        color: white;
      }
    }

    .tab-icon {
      font-size: 28rpx;
      color: #666;
    }

    .tab-text {
      font-size: 28rpx;
      font-weight: 500;
      color: #666;
    }
  }
}

/* 列表区域 */
.list-section {
  flex: 1;
  overflow: hidden;
  padding: 0 32rpx 32rpx;
  display: flex;
  flex-direction: column;

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12rpx;
    margin-bottom: 12rpx;

    .list-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .list-count {
      font-size: 24rpx;
      color: #999;
    }
  }

  .loading-state {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 80rpx 0;

    .loading-text {
      font-size: 28rpx;
      color: #909399;
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 120rpx 0;

    .empty-icon {
      font-size: 120rpx;
      margin-bottom: 24rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #909399;
    }
  }

  .receive-list {
    display: flex;
    flex-direction: column;
    gap: 24rpx;

    .receive-item {
      background-color: #ffffff;
      border-radius: 16rpx;
      padding: 28rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
      }

      .item-header {
        margin-bottom: 20rpx;

        .item-title-row {
          display: flex;
          align-items: center;
          gap: 16rpx;
          margin-bottom: 12rpx;

          .title-text {
            flex: 1;
            font-size: 32rpx;
            font-weight: 600;
            color: #303133;
            line-height: 1.4;
          }

          .read-badge {
            padding: 6rpx 16rpx;
            border-radius: 8rpx;
            font-size: 24rpx;
            background-color: #e6f7ff;
            color: #1890ff;

            &.read {
              background-color: #f0f9ff;
              color: #52c41a;
            }

            .badge-text {
              white-space: nowrap;
            }
          }
        }

        .item-time {
          font-size: 24rpx;
          color: #909399;
        }
      }

      .item-content {
        display: flex;
        flex-direction: column;
        gap: 12rpx;
        margin-bottom: 20rpx;

        .item-desc {
          font-size: 26rpx;
          color: #606266;
          line-height: 1.5;
        }
      }

      .item-footer {
        display: flex;
        justify-content: flex-end;
        padding-top: 16rpx;
        border-top: 1rpx solid #f0f0f0;

        .view-btn {
          font-size: 28rpx;
          color: #1890ff;
          font-weight: 500;
        }
      }
    }
  }

  .load-more {
    display: flex;
    justify-content: center;
    padding: 40rpx 0;

    .load-more-text {
      font-size: 28rpx;
      color: #1890ff;
      padding: 16rpx 40rpx;
      border-radius: 12rpx;
      background-color: #e6f7ff;
    }
  }

  .no-more {
    display: flex;
    justify-content: center;
    padding: 40rpx 0;

    .no-more-text {
      font-size: 26rpx;
      color: #909399;
    }
  }
}
</style>
